package com.graduate.examapp.view.base

import android.graphics.drawable.Drawable
import android.os.Build
import android.os.Bundle
import android.view.View
import android.view.WindowManager
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import com.graduate.examapp.R

/**
 *
 */
open class BaseActivity : AppCompatActivity() {
    open var windowBackgroud: Drawable? = null

    open var lightMode = true
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        addActivity(this)
        windowBackgroud = ContextCompat.getDrawable(this, R.drawable.window_back)
        setStatusBarBackgroud(windowBackgroud)
    }

    override fun onDestroy() {
        super.onDestroy()
        removeActivity(this)
    }

    private fun setStatusBarBackgroud(windowBackgroud: Drawable?) {
        val window = window
        windowBackgroud?.let {
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
            window.statusBarColor = ContextCompat.getColor(this, android.R.color.transparent)
            setStatusBarLightModeOrigin(lightMode)
            //window.setBackgroundDrawable(windowBackgroud)
            window.setBackgroundDrawable(windowBackgroud)
        }
    }

    /** 使用原生系统 API 来设置状态栏文字颜色 */
    private fun setStatusBarLightModeOrigin(lightMode: Boolean) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return
        }
        val decorView = window.decorView
        var originVisibility: Int = decorView.getSystemUiVisibility()
        // 亮色模式，使用黑色文字
        if (lightMode && (originVisibility and  View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR) == 0) {
            originVisibility = originVisibility or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
        }
        // 暗色模式，使用白色文字
        if (!lightMode && (originVisibility and  View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR) != 0) {
            originVisibility = originVisibility xor  View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
        }
        decorView.setSystemUiVisibility(originVisibility);
    }

    companion object {
        private val activities = ArrayList<BaseActivity>()
        fun addActivity(activity: BaseActivity) {
            activities.add(activity)
        }
        fun removeActivity(activity: BaseActivity) {
            activities.remove(activity)
        }
        fun finishAll() {
            for (activity in activities) {
                activity.finish()
            }
            activities.clear()
        }
    }
}